package com.acoffee.filter;

import com.acoffee.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @author acoffee
 * @create 2021-11-07 21:53
 */
@WebFilter("/pages/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        String uri = request.getRequestURI();
        //如果等于null，说明还没有登录
        if (uri.contains("login.jsp") || uri.contains("register.jsp")||uri.contains("active_error.jsp")||uri.contains("active_ok.jsp")||uri.contains("register_ok.jsp")) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            if (user == null) {
                request.getRequestDispatcher("/pages/login.jsp").forward(servletRequest, servletResponse);
                return;
            } else {
                //让程序继续往下访问目标资源
                chain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
